package com.dingreading.cloud.subject.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.dto.StaffLoginDto;
import com.dingreading.cloud.common.util.*;
import com.dingreading.cloud.subject.entity.Staff;
import com.dingreading.cloud.subject.service.AppProjectService;
import com.dingreading.cloud.subject.service.StaffService;
import com.dingreading.cloud.subject.util.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping(value = "/front/staff")
@Api(tags = "门店-员工管理")
public class FrontStaffController {

    @Resource
    private RedisService redisService;
    @Resource
    private StaffService staffService;
    @Resource
    private AppProjectService appProjectService;

    @ApiOperation(value = "获取登录员工的基本信息")
    @PostMapping(value = "/getStaffInfo", produces = "application/json; charset=UTF-8")
    public R<Object> getStaffInfo(
            HttpServletRequest request
    ) {
        // 网页地址
        String htmlUrl = HttpRequestUtil.getHtmlUrl(request);
        if (StringUtils.isBlank(htmlUrl))
            return R.fail("网页地址获取失败");

        // 根据网页地址获取模块id
        String appId = LoginAuthUtil.getAppId(htmlUrl);
        if (StringUtils.isBlank(appId))
            return R.fail("应用Id获取失败");

        // 获取应用的秘钥
        String appSecret = getAppSecret(appId);
        if (StringUtils.isBlank(appSecret))
            return R.fail("应用秘钥获取失败");

        // 获取cookieValue
        Cookie cookie = CookiesUtil.getCookieByName(request, LoginAuthUtil.DDPB_TOKEN);
        if (cookie == null || StringUtils.isBlank(cookie.getValue())) {
            // 获取cookieValue失败，去登录
            String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
            return R.fail(-1, "token校验失败", loginUrl);
        }
        String cookieValue = cookie.getValue();

        // 根据cookieValue获取redis里的登录信息
        LoginDataDto loginDataDto = null;
        String loginStr = (String) redisService.get(RedisParam.STAFF_LOGIN + cookieValue);
        if (StringUtils.isBlank(loginStr)) {
            // 发起请求获取登录信息
            R<Object> r = LoginAuthUtil.getLoginInfo(appId, appSecret, htmlUrl, cookieValue, IpUtil.getIpAddr(request));
            if (R.isError(r))
                return r;

            loginDataDto = (LoginDataDto) r.getData();

            if (loginDataDto == null) {
                // 获取登录信息失效、去登录
                String loginUrl = LoginAuthUtil.getLoginUrl(appId, appSecret, htmlUrl);
                return R.fail(-1, "登录已失效", loginUrl);
            }
            // redis保存10分钟
            redisService.set(RedisParam.STAFF_LOGIN + cookieValue, JsonUtil.toJsonString(loginDataDto), RedisParam.MINUTE_TIME);
        } else {
            // 获取redis里的登录信息
            loginDataDto = JSONObject.parseObject(loginStr, LoginDataDto.class);
        }

        Staff staff = staffService.getByUid(loginDataDto.getStaffUid());
        if (staff == null)
            return R.fail("员工获取失败");

        // 0.普通员工 1.店长 2.市场
        int staffRole = AccountUtil.isStaffRole(loginDataDto.getStoreRoles());
        StaffLoginDto staffLoginDto = new StaffLoginDto();
        staffLoginDto.setCorpUid(loginDataDto.getCorpUid());
        staffLoginDto.setStoreUid(loginDataDto.getCurrentStoreUid());
        staffLoginDto.setStaffUid(loginDataDto.getStaffUid());
        staffLoginDto.setStoreName(loginDataDto.getCurrentStoreName());
        staffLoginDto.setFullName(loginDataDto.getFullName());
        staffLoginDto.setNickName(loginDataDto.getNickName());
        staffLoginDto.setUsername(loginDataDto.getUsername());
        staffLoginDto.setStoreMgr(staffRole);
        staffLoginDto.setPubPhone(staff.getPubPhone());
        staffLoginDto.setPriPhone(staff.getPriPhone());

        return R.ok(staffLoginDto);
    }

    /**
     * 获取应用秘钥
     */
    private String getAppSecret(String appId) {
        String appSecret = (String) redisService.get(RedisParam.APP_PROJECT + appId);
        if (StringUtils.isBlank(appSecret)) {
            appSecret = appProjectService.getAppSecret(appId);

            if (StringUtils.isNotBlank(appSecret))
                redisService.set(RedisParam.APP_PROJECT + appId, appSecret, RedisParam.HOUR_TIME);
        }

        return appSecret;
    }

}
